package com.example.myapplication.tools;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.myapplication.R;
import com.example.myapplication.config.AppConfigurate;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;

import java.io.File;
import java.io.FileNotFoundException;

public class ComSendFileToHttpDialog extends Dialog{

	private final int SNED_FILE = 10;
	
	Context context;
	Handler mainHandler ;
	AsyncHttpClient client;
	int currentIndex;
	Gson gson;
//	DBTools dbTools;
	String ISBNId;
	File file;
	
	public ComSendFileToHttpDialog(Context context, Handler handler, String ISBN, String filePath){
		super(context);
		this.context = context;
//		dbTools = new DBTools(new DatabaseOpenHelper(context));
		mainHandler = handler;
		client = new AsyncHttpClient();
		gson = new Gson();
		currentIndex = 0;
		ISBNId = ISBN;
		file = new File(filePath);
	}

	/**
	 * 上传的文件路径
	 * @param filePath
	 */
	private void sendFile(File filePath){
		tvFileName.setText("正在上传("+ filePath.getName()+ ")");
		RequestParams params = new RequestParams();
    	try {
    		params.put("fileName", filePath);
    		params.put("isbnId", ISBNId);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
//    	filePostAsync(client, "/fs/upload", params, handler, pro,SNED_FILE);
    	filePostAsync(client, "/fs/uploadComPhoto", params, handler, pbItem,SNED_FILE);
	}
	
	static int postTemp = 0;
	public void filePostAsync(AsyncHttpClient client, String method, RequestParams params
			, final Handler handler, final ProgressBar pd, final int flag){
        pd.setIndeterminate(false);
        pd.setMax(100);
        postTemp = 0;
        //TODO:正常使用
    	client.post(AppConfigurate.START_IP + method,params, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int statusCode, Header[] header, byte[] responseBody,
					Throwable error) {
				pd.setProgress(100);
				Message msg = new Message();
				msg.what = WebAsyncHttpUtils.ASYNC_ERROR;
				msg.arg1 = flag;
				handler.sendMessage(msg);
			}

			@Override
			public void onSuccess(int statusCode, Header[] header, byte[] responseBody) {
				Message msg = new Message();
				msg.what = WebAsyncHttpUtils.ASYNC_SUCCESS;
				msg.obj = new String(responseBody);
				msg.arg1 = flag;
				handler.sendMessage(msg);
				System.out.println(new String(responseBody));
			}
			
			@Override
			public void onProgress(long bytesWritten, long totalSize) {
				super.onProgress(bytesWritten, totalSize);
				int test = FileUtils.formatInteger((double)bytesWritten / (double)totalSize);
				if(test > postTemp){
					postTemp = test;
					pd.setProgress(postTemp);
//					pd.notify();
					setTopProgressBar();
				}
			}
    	});
        
//        //TODO:测试使用
//        new Thread(){
//        	public void run() {
//        		for(int i = 0 ; i <= 100 ; i += 5){
//                	try {
//                		Thread.sleep(200);
//					} catch (InterruptedException e) {
//						e.printStackTrace();
//					}
//                	Message msg = new Message();
//                	msg.what = i;
//                	han2.sendMessage(msg);
//                }
//        	};
//        }.start();
        
    }
	
	Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			switch(msg.what){
			case WebAsyncHttpUtils.ASYNC_ERROR:
				switch(msg.arg1){
				case SNED_FILE:
					errorShowName();
					break;
				}
				break;
			case WebAsyncHttpUtils.ASYNC_SUCCESS:
				switch(msg.arg1){
				case SNED_FILE:
					//TODO:正常使用放开
					Message msgResult = new Message();
					msgResult.what = 0;
					mainHandler.sendMessage(msgResult);
					cancel();
					break;
				}
				break;
			}
		};
	};
	
	private void setTopProgressBar(){
		tvItemRamark.setText(pbItem.getProgress() + "/" + 100);
	}
	
	private void errorShowName(){
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("温馨提示");
		String errorStr = file.getName();
		builder.setMessage(errorStr + "上报失败");
		builder.setNegativeButton("确定", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				Message msgResult = new Message();
				msgResult.what = 1;
				mainHandler.sendMessage(msgResult);
				cancel();
			}
		});
		builder.setPositiveButton("重试", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				sendFile(file);
			}
		});
		AlertDialog ad = builder.create();
		ad.setCanceledOnTouchOutside(false);
		ad.show();
	}
	
	ProgressBar pbAll;
	TextView tvAllRamark;
	
	ProgressBar pbItem;
	TextView tvItemRamark;
	
	TextView tvFileName;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
//		if(AppConfigurate.isPad){
			setContentView(R.layout.dialog_send_file_http);
//		}else{
//			setContentView(R.layout.dialog_send_file_http_moblie);
//		}
		pbItem  = (ProgressBar)findViewById(R.id.dialog_progress_item);
		pbAll = (ProgressBar) findViewById(R.id.dialog_progress_all);
		
		tvFileName = (TextView) findViewById(R.id.dialog_item_filename);
		tvItemRamark = (TextView) findViewById(R.id.dialog_remark_item);
		tvAllRamark = (TextView) findViewById(R.id.dialog_remark_all);
		tvAllRamark.setVisibility(View.GONE);
		pbAll.setVisibility(View.GONE);
		findViewById(R.id.dialog_title_all).setVisibility(View.GONE);
		initView();
		sendFile(file);
	}
	
	private void initView(){
		pbAll.setMax(100);
		pbAll.setProgress(0);
		pbItem.setProgress(0);
		currentIndex = 0;
	}
	
}
